package com.appkubes.fintech.admin.application.risk.data.boole.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Des Created by wh_king on 2019/10/16.
 */
public class RSA {
    public static String SIGN_ALGORITHMS = "SHA256withRSA";
    private static String CHAR_SET = "UTF-8";
    private static String CIPHER_MODE = "RSA";

    public static String sign(String content, String privateKey) throws Exception {

        try {

            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
            KeyFactory keyf = KeyFactory.getInstance(CIPHER_MODE);
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(CHAR_SET));

            byte[] signed = signature.sign();

            return Base64.encodeBase64String(signed);

        } catch (Exception ex) {
            throw new Exception(ex.toString());
        }
    }

    /**
     * 1.第json的key 字典排序
     * 2.按排完序的key  获取对应的 value 拼接成字符串
     *
     * @param json
     * @return
     */
    public static String getSignContent(JSONObject json) {
        List<String> keys = new ArrayList<>(json.size());
        for (Map.Entry<String, Object> entry : json.entrySet()) {
            String s = entry.getKey();
            if (!s.equals("sign")) {
                keys.add(s);
            }
        }

        Collections.sort(keys);

        StringBuilder sb = new StringBuilder();

        for (String key : keys) {
            Object v = json.get(key);
            if (v instanceof JSONObject || v instanceof JSONArray) {
                sb.append(JSON.toJSONString(v, SerializerFeature.MapSortField));
            } else {
                sb.append(v == null ? "" : v.toString());
            }
        }

        return sb.toString();
    }

}
